package config;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.loser.utils.trace.MDCUtil;
import com.loser.utils.trace.TraceUtil;
import org.springframework.core.annotation.Order;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(1)
@WebFilter(urlPatterns = "/*", filterName = "traceIdFilter")
public class TraceIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String traceId = httpRequest.getHeader(MDCUtil.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = TraceUtil.getTraceId();
        }
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader(MDCUtil.TRACE_ID, traceId);
        try {
            MDCUtil.setTraceId(traceId);
            chain.doFilter(request, response);
        } finally {
            MDCUtil.removeTraceId();
        }
    }
}
